import argparse
import json
import os
from dora import Node
from mofa.kernel.utils.log import write_agent_log
from mofa.kernel.utils.util import load_agent_config, create_agent_output
from mofa.run.run_agent import run_dspy_agent, run_crewai_agent, run_dspy_or_crewai_agent
from mofa.utils.files.read import read_yaml
import pyarrow as pa
import os
from mofa.utils.files.dir import get_relative_path
from mofa.utils.log.agent import record_agent_prompt_log, record_agent_result_log
#import tkinter as tk
#from tkinter import messagebox, scrolledtext
import re

RUNNER_CI = True if os.getenv("CI") == "true" else False
def show_long_message(title, message):
    return
    root = tk.Tk()
    root.title(title)
    
    # 创建滚动文本框
    text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=800, height=200)
    text_area.pack(padx=10, pady=10)
    text_area.insert(tk.END, message)
    text_area.config(state=tk.DISABLED)  # 设置为只读
    
    # 创建关闭按钮
    button = tk.Button(root, text="Close", command=root.destroy)
    button.pack(pady=10)
    
    root.mainloop()

def main():
    inputs = {}
    agent_result = {}
    results = {}
    # Handle dynamic nodes, ask for the name of the node in the dataflow, and the same values as the ENV variables.
    parser = argparse.ArgumentParser(description="Reasoner Agent")

    parser.add_argument(
        "--name",
        type=str,
        required=False,
        help="The name of the node in the dataflow.",
        default="arrow-assert",
    )
    parser.add_argument(
        "--task",
        type=str,
        required=False,
        help="Tasks required for the Reasoner agent.",
        default="Paris Olympics",
    )

    args = parser.parse_args()
    task = os.getenv("TASK", args.task)

    node = Node()  # provide the name to connect to the dataflow if dynamic node

    # assert_data = ast.literal_eval(data)
    file_str = ''
    code_str = ''
    code_json_str = ''
    for event in node:
        if event["type"] == "INPUT":
            if event['id'] in ['output2']:
                usertask = event["value"][0].as_py()
                code = event["value"][1].as_py()
                task2 = f"请根据相关代码文件完成{usertask}，相关代码文件如下：{code_json_str}"
                show_long_message("Analysis Information", f"Task: {task2}")
                inputs['task'] = task2
                record_agent_prompt_log(agent_config=inputs, config_file_path=yaml_file_path, log_key_name='Agent Prompt',
                                        task=task2)

                agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
                show_long_message("Analysis Information", f"Agent Result: {agent_result}")
                record_agent_result_log(agent_config=inputs,
                                        agent_result={inputs.get('log_step_name', "Step_one"): agent_result})
                
                results['task'] = task2
                results['result'] = agent_result
                print('agent_output:', results)
                node.send_output("raw_code", pa.array([agent_result,task]), event['metadata']) 
            elif event['id'] in ['output']:
                file_str = event["value"][0].as_py()
                code_str = event["value"][1].as_py()
                show_long_message("Analysis Information", f"File:{file_str} Code: {code_str}")
                # 提取 JSON 数组部分
                json_array_str = re.search(r'\[\s*{.*}\s*\]', file_str, re.DOTALL).group()

                # 解析 JSON 字符串
                file_paths = json.loads(json_array_str)
                code_contents = json.loads(code_str)

                # 创建一个字典来映射文件路径到内容
                content_dict = {item['path']: item['content'] for item in code_contents}

                # 创建一个列表来存储有对应内容的文件
                result = []

                # 查找并添加每个文件路径对应的内容
                for file_info in file_paths:
                    path = file_info['path']
                    content = content_dict.get(path)
                    if content:
                        result.append({"path": path, "content": content})

                # 将结果转换为 JSON 字符串
                code_json_str = json.dumps(result, ensure_ascii=False, indent=4)
                task2 = f"请根据相关代码文件完成{task}，相关代码文件如下：{code_json_str}"
                show_long_message("Analysis Information", f"Task: {task2}")
                inputs['task'] = task2
                record_agent_prompt_log(agent_config=inputs, config_file_path=yaml_file_path, log_key_name='Agent Prompt',
                                        task=task2)

                agent_result = run_dspy_or_crewai_agent(agent_config=inputs)
                show_long_message("Analysis Information", f"Agent Result: {agent_result}")
                record_agent_result_log(agent_config=inputs,
                                    agent_result={inputs.get('log_step_name', "Step_one"): agent_result})
                node.send_output("raw_code", pa.array([agent_result,task,code_json_str]), event['metadata']) 

            elif event['id'] in ['task','data','reasoner_task']:
                task = event["value"][0].as_py()
                yaml_file_path = get_relative_path(current_file=__file__, sibling_directory_name='configs',
                                                target_file_name='code_assistant_agent.yml')
                inputs = load_agent_config(yaml_file_path)
                show_long_message("Analysis Information", f"{inputs}")
                show_long_message("Task Information", f"Task: {task}")
                #print(inputs)
                node.send_output("get_code", pa.array([task]), event['metadata'])
if __name__ == "__main__":
    main()
#帮我为1.py集成复数乘法